﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using GdHotel.Data.Interfaces;
using GdHotel.Data.Meta;

namespace GdHotel.Data.Repositories
{
    public class ImagesRepository : IImagesRepository
    {
        private String[] extensions = new[] { "*.gif", "*.jpg", "*.jpeg", "*.png" };
        
        public String DirectoryName { get; set; }
        public String RelativePathPrefix { get; set; }

        public ImagesRepository()
        {
            DirectoryName = "";
            RelativePathPrefix = "";
        }

        public ImagesRepository(String directoryName, String relativePathPrefix)
        {
            DirectoryName = directoryName;
            RelativePathPrefix = relativePathPrefix;
        }

        public IEnumerable<ImageModel> FindAll()
        {
            var result = new List<ImageModel>();
            
            DirectoryInfo directory = new DirectoryInfo(DirectoryName);
            if (!directory.Exists)
                return result;

            foreach (var extension in extensions)
            {
                var files = directory.GetFiles(extension, SearchOption.TopDirectoryOnly);
                foreach (var file in files)
                {
                    var bitmap = Image.FromFile(file.FullName);
                    try
                    {
                        ImageModel image = new ImageModel {FileName = file.Name, Url = RelativePathPrefix + file.Name, Width = bitmap.Width, Height = bitmap.Height};
                        result.Add(image);
                    }
                    finally
                    {
                        bitmap.Dispose();
                    }
                }
            }

            return result.OrderBy(f => f.FileName);
        }
    }
}
